<template>
  <div class="login-content">
    <!--    <h1>联合授权登录中，请稍后～</h1>-->
  </div>
</template>

<script>
import {
  loginPost,
  mlogin,
  sendMsg
} from '../../api/login';
import { Loading } from 'element-ui';
import {
  getPermission
} from '../../api/user';
var loginRequest = {
  url: '/usercenter/login'
};
var sendMsgRequest = {
  url: '/usercenter/sendmsg/{id}'
};
var phoneLogin = {
  url: '/usercenter/loginMsg'
};
var perRequest = {
  url: '/usercenter/user-permission/current-user-permission'
};
let Base64 = require('js-base64').Base64;

export default {

  data: function () {
    var checkPhone = (rule, value, callback) => {
      const reg = /^0?(13[0-9]|15[012356789]|18[0-9]|14[578]|16[6]|17[035768]|19[19])[0-9]{8}$/
      if (reg.test(value)) {
        return callback();
      }
      callback('请输入合法的手机号');
    };
    return {
      param: {
        phone: '',
        code: ''
      },
      rules: {
        phone: [{
          validator: checkPhone,
          required: true,
          trigger: 'blur'
        }],
        code: [{
          required: true,
          message: '请输入验证码',
          trigger: 'blur'
        }]
      },
      dialogVisible: false, // 对话框显示和隐藏
      valiBtn: '获取验证码',
      disabled: false,
      // rules: {
      // 	username: [{
      // 		required: true,
      // 		message: '请输入用户名',
      // 		trigger: 'blur'
      // 	}],
      // 	password: [{
      // 		required: true,
      // 		message: '请输入密码',
      // 		trigger: 'blur'
      // 	}]
      // },
      permission: {}
    };
  },
  mounted() {


    let openkey = localStorage.getItem('openKey')

    if (openkey) {
      let loading = Loading.service({ text: '登录中' });
      // this.$message.warning('联合登录中');
      mlogin({
        openKey: openkey
      })
          .then((res) => {
            loading.close();
            switch (res.code) {
              case 0:
                // //登录成功，写入token

                // this.$message.success('登录成功');
                let phone = this.param.phone ? this.param.phone : '社智在线用户'
                localStorage.setItem('ms_username', phone);
                localStorage.setItem('token', res.data.token);
                let level = res.data.superManager == 1 ? process.env.superManager : res.data.level
                localStorage.setItem('level', level);
                localStorage.setItem('superManager', res.data.superManager);
                localStorage.setItem('userid', res.data.uid);
                localStorage.setItem('is_szzx',1);
                localStorage.setItem('nickName', res.data.nickName);
                getPermission(perRequest).then((res2) => {
                  localStorage.setItem('userPermissions', JSON.stringify(res2
                      .data));
                  this.setUserPermission(res2.data);
                  let newUrl = localStorage.getItem('newUrl');
                  if(newUrl){
                    newUrl = decodeURIComponent(newUrl)
                    window.open(newUrl,'_self');
                    return ;
                  }else{
                    this.$router.push('/home');
                  }

                });
                localStorage.removeItem('openKey')
                // this.$router.push('/');
                break;
              case 200003:
                //用户名密码错误
                this.$message.error(res.message);
                break;
              case 200011:
                this.$message.error(res.message);
                break;
              case 200012:
                this.$message.error(res.message);
                break;
              case 200004:
                //用户被禁用
                this.$message.error(res.message);
                this.$message.error('请联系管理员');
                break;
              default:

                //系统维护中，跳页面吧
                this.$router.push('/loginmsg');
            }
          })
          .catch((error) => {
            localStorage.removeItem('openKey')
            this.$message.error(error.message);
            return Promise.reject();
          });
    } else {
      this.$router.push('/login');
    }
  },
  methods: {

    setUserPermission(userPermissionList) {
      this.doSetUserPermission(userPermissionList);
      sessionStorage.setItem('permission', JSON.stringify(this.permission));
      //sessionStorage.permission = JSON.stringify(this.permission);
    },
    doSetUserPermission(userPermissionList) {
      //逐级遍历
      for (var i = 0; i < userPermissionList.length; i++) {
        //若不是顶级，将冒号转化为层级关系
        this.toLevelShow(userPermissionList[i].permissionCode);
        //如果还有子集，进行递归设置
        if (userPermissionList[i].children.length > 0) {
          this.doSetUserPermission(userPermissionList[i].children);
        }
      }
    },
    toLevelShow(code) {
      var codeArr = code.split(':');
      if (codeArr.length == 1) {
        this.permission[codeArr[0]] = true;
      } else if (codeArr.length == 2) {
        if (typeof this.permission[codeArr[0]] == 'undefined' || this.permission[codeArr[0]] == true) {
          this.permission[codeArr[0]] = {};
        }
        this.permission[codeArr[0]][codeArr[1]] = true;
      } else if (codeArr.length == 3) {
        if (typeof this.permission[codeArr[0]] == 'undefined' || this.permission[codeArr[0]] == true) {
          this.permission[codeArr[0]] = {};
        }
        if (typeof this.permission[codeArr[0]][codeArr[1]] == 'undefined' || this.permission[codeArr[0]][
            codeArr[1]
            ] == true) {
          this.permission[codeArr[0]][codeArr[1]] = {};
        }
        this.permission[codeArr[0]][codeArr[1]][codeArr[2]] = true;
      }
    },

  }
};
</script>

<style scoped>
.login-content {
  position: relative;
  width: 100%;
  height: 100%;
  text-align: center;
  padding-top: 20%;
}
</style>